package com.lej.home.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import com.lej.core.utils.KLog

class MoveView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val pos = FloatArray(2)//点击事件触发坐标
    private val currentPos = IntArray(2)//目标view的左上角坐标
    private var checkList: Array<out ViewGroup>? = null

    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_UP) {
            pos[0] = event.rawX
            pos[1] = event.rawY
        }
        return super.dispatchTouchEvent(event)
    }

    fun setCheckList(vararg list: ViewGroup) {
        checkList = list
    }

    init {
        super.setOnClickListener click@{ checkList?.forEach { if (it.checkClick()) return@click } }
    }

    private fun ViewGroup.checkClick(): Boolean {
        KLog.e("sss", "test $this")
        for (child in children) {
            child.getLocationOnScreen(currentPos)
            if (currentPos[0] > pos[0] ||
                currentPos[1] > pos[1] ||
                currentPos[0] + child.width < pos[0] ||
                currentPos[1] + child.height < pos[1]
            ) continue
            if (child is ViewGroup) if (child.checkClick()) return true//深度优先遍历

            if (child.performClick()) {
                KLog.e("sss----", "test $child")
                return true
            }
        }
        return false
    }

    override fun setOnClickListener(l: OnClickListener?) {}//屏蔽外界的点击事件
}